package com.hanxu.mallware.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.hanxu.common.constant.WareConstant;
import com.hanxu.common.utils.R;
import com.hanxu.mallware.dao.PurchaseDetailDao;
import com.hanxu.mallware.dao.WareSkuDao;
import com.hanxu.mallware.entity.PurchaseDetailEntity;
import com.hanxu.mallware.entity.WareSkuEntity;
import com.hanxu.mallware.feign.ProductFeignService;
import com.hanxu.mallware.service.PurchaseDetailService;
import com.hanxu.mallware.vo.MergeVo;
import com.hanxu.mallware.vo.PurchaseDoneVo;
import com.hanxu.mallware.vo.PurchaseItemDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.beans.Transient;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hanxu.common.utils.PageUtils;
import com.hanxu.common.utils.Query;

import com.hanxu.mallware.dao.PurchaseDao;
import com.hanxu.mallware.entity.PurchaseEntity;
import com.hanxu.mallware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailDao purchaseDetailDao;
    @Autowired
    private WareSkuDao wareSkuDao;
    @Autowired
    private ProductFeignService productFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceiveList(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status", 0).or().eq("status", 1)
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        if (purchaseId == null) {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.baseMapper.insert(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }
        //TODO 确认采购单状态是0,1才能够合并
        List<Long> items = mergeVo.getItems();
        Long finalPurchaseId = purchaseId;
        for (Long item : items) {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(item);
            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            purchaseDetailDao.updateById(purchaseDetailEntity);
        }
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.baseMapper.updateById(purchaseEntity);
    }

    @Override
    public void received(List<Long> ids) {
        // 确认当前采购单是新建或者已分配状态
        for (Long id : ids) {
            PurchaseEntity purchaseEntity = this.baseMapper.selectById(id);
            if (purchaseEntity.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() ||
                    purchaseEntity.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {
                purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.RECEIVED.getCode());
                purchaseEntity.setUpdateTime(new Date());
                // 改变采购单的状态
                this.baseMapper.updateById(purchaseEntity);
                // 改变采购项的状态
                List<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailDao.selectList(new QueryWrapper<PurchaseDetailEntity>().eq("purchase_id", id));
                for (PurchaseDetailEntity purchaseDetailEntity : purchaseDetailEntities) {
                    PurchaseDetailEntity purchaseDetailEntity1 = new PurchaseDetailEntity();
                    purchaseDetailEntity1.setId(purchaseDetailEntity.getId());
                    purchaseDetailEntity1.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                    purchaseDetailDao.updateById(purchaseDetailEntity1);
                }
            }
        }
    }

    @Override
    public void done(PurchaseDoneVo purchaseDoneVo) {
        // 改变采购项状态
        Boolean flag=true;
        List<PurchaseItemDoneVo> purchaseItemDoneVos=purchaseDoneVo.getItems();
        for (PurchaseItemDoneVo purchaseItemDoneVo : purchaseItemDoneVos) {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            if(purchaseItemDoneVo.getStatus()==WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()){
                flag=false;
                purchaseDetailEntity.setStatus(purchaseItemDoneVo.getStatus());
            }else{
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISHED.getCode());
                // 将成功采购的进行入库
                PurchaseDetailEntity entity = purchaseDetailDao.selectById(purchaseItemDoneVo.getItemId());
                // 判断如果还没有这个库存记录，就新增
                List<WareSkuEntity> wareSkuEntities = wareSkuDao.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", entity.getSkuId()).eq("ware_id", entity.getWareId()));
                if(wareSkuEntities==null||wareSkuEntities.size()==0){
                    WareSkuEntity wareSkuEntity = new WareSkuEntity();
                    wareSkuEntity.setSkuId(entity.getSkuId());
                    wareSkuEntity.setWareId(entity.getWareId());
                    wareSkuEntity.setStock(entity.getSkuNum());
                    wareSkuEntity.setStockLocked(0);
                    // 远程查询sku的name
                    // 自己处理异常
                    try{
                        R info = productFeignService.info(entity.getSkuId());
                        Map<String, Object> skuInfo = (Map<String, Object>) info.get("skuInfo");
                        if(info.getCode()==0){
                            wareSkuEntity.setSkuName((String) skuInfo.get("skuName"));
                        }
                    }catch (Exception e){

                    }
                    wareSkuDao.insert(wareSkuEntity);
                }else{
                    wareSkuDao.addStock(entity.getSkuId(),entity.getWareId(),entity.getSkuNum());
                }
            }
            purchaseDetailEntity.setId(purchaseItemDoneVo.getItemId());
            purchaseDetailDao.updateById(purchaseDetailEntity);
        }
        // 改变采购单状态
        Long id=purchaseDoneVo.getId();
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        purchaseEntity.setUpdateTime(new Date());
        purchaseEntity.setStatus(flag?WareConstant.PurchaseStatusEnum.FINISHED.getCode():WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        this.baseMapper.updateById(purchaseEntity);


    }

}